<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单创建时间" prop="orderTime">
        <el-date-picker clearable
          v-model="queryParams.orderTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择订单创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="备注" prop="remake">
        <el-input
          v-model="queryParams.remake"
          placeholder="请输入备注"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否删除" prop="isDel">
        <el-input
          v-model="queryParams.isDel"
          placeholder="请输入是否删除"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单ID" align="center" prop="orderId" />
      <el-table-column label="订单编号" align="center" prop="orderCode" />
      <el-table-column label="用户名称" align="center" prop="userName" />
      <el-table-column label="商品名称" align="center" prop="skuName" />
      <el-table-column label="订单价格" align="center" prop="sumPrice" />
      <el-table-column label="订单创建时间" align="center" prop="orderTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderStatus" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.orderStatus==1">待付款</span>
          <span v-if="scope.row.orderStatus==2">已付款</span>
          <span v-if="scope.row.orderStatus==3">已发货</span>
          <span v-if="scope.row.orderStatus==4">已完成</span>
          <span v-if="scope.row.orderStatus==5">已关闭</span>
          <span v-if="scope.row.orderStatus==6">退款中</span>
          <span v-if="scope.row.orderStatus==7">退款成功</span>
          <span v-if="scope.row.orderStatus==8">退款失败</span>
          <span v-if="scope.row.orderStatus==9">取消订单</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remake" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['order:order:remove']">删除</el-button>
          <el-button @click="orderPayment(scope.row)" v-if="scope.row.orderStatus === 1">支付</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <el-dialog title="结算页面" :visible.sync="dialogFormVisible" width="80%">

      <!--      回显不管-->
      <el-table :data="cartList" width="80%">
        <el-table-column property="skuNum" label="商品数量" width="210"></el-table-column>
        <el-table-column property="inputPrice" label="商品单价" width="210"></el-table-column>
        <el-table-column property="skuTotalPrice" label="商品总价" width="300"></el-table-column>
        <el-table-column property="skuName" label="商品名称" width="300"></el-table-column>
        <el-table-column label="商品图片" align="center" prop="imgUrl" width="300">
          <template slot-scope="scope">
            <image-preview :src="scope.row.skuImg" :width="50" :height="50"/>
          </template>
        </el-table-column>
      </el-table>

      <template>
        <div class="form-container">
          <el-form :model="orderDetails" label-width="100px">
            <el-form-item label="订单编号">
              <el-input v-model="orderCode"></el-input>
            </el-form-item>
            <el-form-item label="订单金额">
              <el-input v-model="orderDetails.orderPrice"></el-input>
            </el-form-item>
            <el-form-item label="实际金额">
              <el-input v-model="orderDetails.paidAmount"></el-input>
            </el-form-item>
            <el-form-item label="是否用优惠券">
              <el-switch v-model="delivery"  @change="isSelectCoupon()"></el-switch>
            </el-form-item>
            <el-form-item label="优惠券" v-if="delivery">
              <el-select v-model="coupon" value-key="couponId" placeholder="请选择活动区域"  @change="selectCoupon(coupon)" >
                <el-option v-for="item in couponList" :key="item.couponId" :value="item" :label="item.couponName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户地址选择">
              <el-select v-model="taskItem" value-key="0" placeholder="请选择用户区域" @change="taskUpd(taskItem)" default-first-option>
                <el-option label="无选择" :key="0" value=""></el-option>
                <el-option v-for="item in taskList" :key="item.takeId" :label="'地址:'+item.takeAddress+',用户名:'+item.takeName+',手机号:'+item.takePhone" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="收货人">
              <el-input v-model="orderDetails.takeName"></el-input>
            </el-form-item>
            <el-form-item label="收货地址">
              <el-input v-model="orderDetails.takeAddress"></el-input>
            </el-form-item>
            <el-form-item label="收货电话">
              <el-input v-model="orderDetails.takePhone"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="Checkout(1)">现在结账</el-button>
      </div>

    </el-dialog>
    <el-button type="primary" @click="orderPayment">确 定</el-button>
  </div>
</template>

<script>
import {
  listOrder,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
  pay,
  getUserTakeList,
  getCartOrderList
} from "@/api/order/order";
import {orderGetDetailInstall} from "@/api/shopping/shoppingCartList";
import {computeCoupon, getUserCouponList} from "@/api/marketing/coupon";
import {getInfo} from "@/api/login";

export default {
  name: "Order",
  data() {
    return {
      //用户编号
      userId:undefined,
      //弹出框开关
      dialogFormVisible: false,
      //输入框长度
      formLabelWidth: '120px',
      //地址列表
      taskList:[],
      //地址
      taskItem:{},
      //订单编号
      orderCode: null,
      //优惠卷开关 发生改变调用方法清空优惠卷
      delivery: false,
      //订单详情
      orderDetails:{
        orderId:null,//订单id
        couponId:null,//优惠券id
        orderPrice:null,//订单金额
        paidAmount:null,//实际金额
        payType:"支付宝",//默认支付宝
        confirmReceiptTime:null,//默认15天
        takeName:null,//收货地址
        takeAddress:null,//收货人电话
        takePhone:null
      },
      //支付宝需要的参数
      zhifubao:{
        paidAmount: '',     //实际金额
        skuName: '',     //sku名: null
        orderCode: ''
      },
      //优惠卷下拉款选中的对象
      coupon:{},
      //优惠卷动态下拉框
      couponList:[],
      //策略接口的参数对象
      computeReq:{
        couponTypeId: null,   //优惠卷类型
        discountAmount: null,   //满减金额
        discountPerentage: null,  //折扣百分比
        minOrderAmount: null,   //所需最低金额
        orderPrice: null  //原价格
      },
      //商品数据
      cartList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        orderCode: null,
        sumPrice: null,
        orderTime: null,
        orderStatus: null,
        remake: null,
        isDel: null,
        skuName: null,

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getUserInfo();
  },
  methods: {
    //是否选择优惠卷
    isSelectCoupon(){
      if(this.delivery===false){
        this.orderDetails.paidAmount=this.orderDetails.orderPrice;
      }
    },
    //点击支付弹出页面
    orderPayment(order){
      //清空表
      this.orderNull()
      this.getTakeList()
      this.getCouponList()

      //获取到订单信息
      //订单信息赋值
      this.orderCode=order.orderCode;
      this.orderDetails.orderId=order.orderId;
      this.orderDetails.orderPrice=order.sumPrice;
      this.orderDetails.paidAmount=order.sumPrice;
      this.zhifubao.paidAmount=order.sumPrice;
      this.zhifubao.skuName=order.skuName;
      console.log(this.orderCode)
      //查询sku数据
      getCartOrderList(order.orderId,this.userId).then(res=>{
        this.cartList=res.data
        console.log(this.cartList)
      })
      this.dialogFormVisible = true
    },

    /** 用户选择用户卷结算 */
    selectCoupon(coupon){
      // 策略接口调用
      console.log(coupon);
      this.computeReq.minOrderAmount=coupon.minOrderAmount;
      this.computeReq.couponTypeId= coupon.couponTypeId;
      this.computeReq.orderPrice = this.orderDetails.orderPrice;
      this.computeReq.discountPerentage=coupon.discountPerentage;
      this.computeReq.discountAmount=coupon.discountAmount;
      computeCoupon(this.computeReq).then(res=>{
        if(res.code==200){
          this.$message.success(res.msg);
          this.orderDetails.paidAmount=res.data;
        }
      })
      //往下调用策略接口
    },

    /**
     * 下单执行流程
     * @param Type
     * @constructor
     */
    Checkout(Type){
      if (Type==1){
        pay(this.orderCode)
        {
          this.zhifubao.paidAmount=this.orderDetails.paidAmount;
          window.open('http://localhost:9205/alipay/pay?&subject='+this.zhifubao.skuName+'&traceNo='+this.orderCode+'&totalAmount=' + this.zhifubao.paidAmount)
        }
        orderGetDetailInstall(this.orderDetails).then(res=>{
          if(res.data.code==200){
            this.$message.success("下单成功")
            this.dialogFormVisible=false
            this.getList()
            this.orderNull()
          }else {
            this.$message.error("下单失败");
            this.dialogFormVisible=false
          }
        })

      }else{

      }

    },

    //清空信息单
    orderNull(){
      this.orderDetails={
        orderId: null,    //订单id
        couponId: null,     //优惠券id
        orderPrice: null,     //订单金额
        paidAmount: null,     //实际金额
        payType: "支付宝",    //默认支付宝
        confirmReceiptTime: null, //收货人
        takeName: null,    //收货地址
        takeAddress: null,//收货人电话
        takePhone: null
      }
    },
    /**
     * 获取地址赋值给订单详情表
     * @param taskItem
     */
    taskUpd(taskItem){

      this.orderDetails.takeName=taskItem.takeName
      this.orderDetails.takeAddress=taskItem.takeAddress
      this.orderDetails.takePhone=taskItem.takePhone
      console.log(taskItem)

    },
    /**
     * 获取地址
     */
    getTakeList(){
      getUserTakeList(this.userId).then(res=>{
        this.taskList=res.data
      })
    },

    getUserInfo(){
      getInfo().then(res=>{
        this.userId=res.data.user.userId;
        console.log(this.userId)
        this.getList();
      })
    },

    /** 获取用户所有的优惠卷*/
    getCouponList(){
      getUserCouponList(this.userId).then(res=>{
        this.couponList=res.data;
      })
    },

    /** 查询订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        userId: null,
        orderCode: null,
        orderTime: null,
        orderStatus: null,
        remake: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDel: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids
      getOrder(orderId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除订单编号为"' + orderIds + '"的数据项？').then(function() {
        return delOrder(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('order/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
